<?php

namespace App\Service\Fee\Import;

use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Models\Fee\FeeAnnualOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\StartBusiness\OpenShopStartBusinessModel;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;

class CheckImportShopStartBusiness
{
    public int $total = 0;

    public int $success = 0;

    public function collection(Collection $collection, ?Command $command)
    {
        $collection->first()->map(function ($item, $row) {
            $row = $row + 1;
            if ($row == 1) {
                return null;
            }
            ++$this->total;
            // 常规内容校验
            list($shopCode, $shopName, $endTime, $shouldPayPrice, $payPrice, $remain) = $item;

            $endTime = self::convertExcelDate($endTime);

            if ($shopCode == null) {
                dump('循环次数' . $this->total);
                dump('成功次数' . $this->success);
                dd('执行结束');
            }


            //通过shopCode反查shopId
            $signOrderModel = OpenShopSignOrderModel::query()
                ->where('status', '!=', SignOrderEnum::ORDER_STATUS_NO)
                ->where('shopCode', $shopCode)
                ->with(['mainProcessRel'])
                ->first();

            if ($signOrderModel->mainProcessRel == null) {
                dump('门店Code为>' . $shopCode . '门店名称为-' . $shopName . '的店铺未找到');
                return null;
            }

            $mainProcessId = $signOrderModel->mainProcessRel->id;

            if (!$mainProcessId) {
                dump('门店Code为>' . $shopCode . '门店名称为-' . $shopName . '的店铺未找到');
                return null;
            }

            //根据mainProcess查询
            $startBusinessTime = (int)OpenShopStartBusinessModel::query()
                ->where('mainProcessId', $mainProcessId)
                ->value('startBusinessTime');

            if (date('md', $endTime) != date('md', $startBusinessTime)) {
                dump('门店Code为>' . $shopCode . '门店名称为-' . $shopName . '门店主流程ID-' . $mainProcessId . '的店铺开业时间与过期时间--《不一致》');
            } else {
                dump('门店Code为>' . $shopCode . '门店名称为-' . $shopName . '的店铺开业时间与过期时间--《一致》');
            }

        })->filter();
    }

    private function convertExcelDate(?int $excelDate): int
    {
        $excelInitDate = 25569; // 1970的值

        if ($excelDate) {
            $excelTime = strtotime(date('Ymd', ($excelDate - $excelInitDate) * 86400 + 8 * 3600));
        } else {
            $excelTime = 0;
        }

        return (int)$excelTime;
    }
}
